import sys
from os import path
from StringIO import StringIO

import logging
import logging.config
log = logging.getLogger(__name__)

from pyglons import app, config

from configobj import ConfigObj
from validate import Validator

import pyglet


configspec = StringIO("""
[window]
width = integer(default=640)
height = integer(default=480)

[data]
images = string(default="data/images")
video = string(default="data/video")
audio = string(default="data/audio")

[debug]
events = boolean(default=False)
skip_splash = boolean(default=False)
""")


def load_config():
    configfilename = None

    if len(sys.argv) > 0:
        configfilename = sys.argv[1]
    else:
        userfile = path.expanduser(path.join('~', '.brick.ini'))
        if path.exists(userfile):
            configfilename = userfile

    # set this to false to not load the the logging config from 
    # the config file
    # FIXME! logging config from file doesnt seem to work...
    if False:
        logging.config.fileConfig(configfilename)
    else:
        logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(name)s %(levelname)s %(message)s')

    configfile = ConfigObj(configfilename, configspec=configspec)
    configfile.validate(Validator())

    config.update(configfile.dict())
    log.debug("config = %s " % str(configfile.dict()))

    for key, value in config['data'].iteritems():
        log.debug('adding %s to resource.path' % value)
        pyglet.resource.path.append(value)
    pyglet.resource.reindex()

    return configfile


